import SparkMD5 from "spark-md5";


class FileTool {

    constructor(chunkSize) {
        this.chunkSize = chunkSize || (1024*1024*5)
    }

    chunk(file) {
        const chunkList = []
        let cur = 0
        let index = 0
        while (cur < file.size) {
            chunkList.push({
                file: file.slice(cur, cur + this.chunkSize),
                seq: index
            })
            index++
            cur += this.chunkSize
        }
        return chunkList
    }

    md5(chunkList) {
        return new Promise(resolve => {
            const spark = new SparkMD5.ArrayBuffer()
            let index = 0
            const load = () => {
                const reader = new FileReader()
                reader.readAsArrayBuffer(chunkList[index].file)
                reader.onload = e => {
                    index++
                    spark.append(e.target.result)
                    // 如果文件处理完成则发送发送请求
                    if (index === chunkList.length) {
                        resolve(spark.end())
                        return
                    }
                    load()
                }
            }
            load()
        })
    }

}

const fileTool = new FileTool()

export default fileTool